(function($){

    $.fn.extend({
        hsInput : function(options, arg) {
            if (typeof(options) == "object") {
                options = $.extend({}, $.hsInput.defaults, options);
            }
            this.each(function() {
                for (var fld in options) {
                    jQuery(this).attr("plugin_" + fld, options[fld]);
                }
                new $.hsInput(this, options, arg);
            });
            return;
        }
    });

    $.hsInput = function(item, options, arg) {
        var myId = item.id;
        var selectId = myId + "_select";
        var loadedHS2 = [];
        var openedHS2 = [];
        var changed = false;
        if (jQuery(item).val() == "") {
            jQuery(item).val(options.defaulttext);
            jQuery(item).removeClass("textentered");
            jQuery(item).attr("datavalue", "");
        } else {
            jQuery(item).addClass("textentered");
            jQuery(item).attr("datavalue", jQuery(item).val());
        }
        var hideList = function() {
            jQuery("div[id='" + selectId + "']").hide( "fade", {}, 300);
        }
        jQuery(item).focus(function() {
            if (jQuery(this).val() == options.defaulttext) {
                jQuery(this).val("");
            }
            if (options.emptyOnFocus) {
                jQuery(this).val("");
            }
        });
        jQuery(item).blur(function() {
            if (jQuery(this).val() == options.defaulttext || jQuery(this).val() == "") {
                jQuery(this).val(options.defaulttext);
                jQuery(this).removeClass("textentered");
                jQuery(this).attr("datavalue", "");
            } else {
                jQuery(this).attr("datavalue", jQuery(this).val());
            }
        });
        jQuery(item).change(function() {
            changed = true;
        });
        var showHS2Selection = function(params, options) {
            callService(options.page, options.hs2service, {
                inputHS : getHS2FromHS4(params.inputHS)
            }, {
                success : function(data) {
                    var attached = jQuery("input#" + myId);
                    var pos = jQuery("table.searchpanel").offset();
                    var attachedpos = attached.offset();
                    jQuery("div[id='" + selectId + "']")
                        .show("fade", {}, 300)
                        .css({
                            position : "absolute",
                            height : "200px",
                            width : "890px",
                            top : Math.floor(attachedpos.top) + 30 + parseInt(options.offsetTop, 10),
                            left : Math.floor(pos.left) + 25 + parseInt(options.offsetLeft, 10),
                            zIndex : 200
                        })
                    ;
                    jQuery("div[id='" + selectId + "']").empty();
                    for (var i = 0; i < data.items.length; i++) {
                        addHS2Item(jQuery("div[id='" + selectId + "']"), data.items[i]);
                    }
                    if (params.inputHS.length > 2) {
                        hs2clicked(getHS2FromHS4(params.inputHS));
                    }
                }
            });
        }

        var showHS4Selection = function(params) {
            callService(options.page, options.freetextservice, params, {
                success : function(data) {
                    var attached = jQuery("input[id='" + myId + "']");
                    var pos = jQuery(item).offset();
                    var attachedpos = attached.offset();
                    jQuery("div[id='" + selectId + "']")
                        .show("fade", {}, 300)
                        .css({
                            position : "absolute",
                            height : "200px",
                            width : "890px",
                            top : Math.floor(attachedpos.top) + 30,
                            left : Math.floor(pos.left),
                            zIndex : 100
                        })
                    ;
                    jQuery("div[id='" + selectId + "']").empty();
                    for (var i = 0; i < data.items.length; i++) {
                        jQuery("div[id='" + selectId + "']").append(
                            jQuery("<div>")
                                .attr("id", data.items[i].hscode)
                                .html(data.items[i].hscode + " - " + data.items[i].description_en + " <b>-</b> " + data.items[i].description_hu)
                                .click(function() { hs4selected(this); })
                                .mouseover(function() { jQuery(this).addClass("highlighted"); })
                                .mouseout(function() { jQuery(this).removeClass("highlighted"); })
                            )
                        ;
                    }
                }
            });
        }

        jQuery("select[id='" + selectId + "']").click(function() {
//            jQuery("input#" + myId).val(jQuery("select#" + selectId + " option:selected").text().split(" - ")[2]);
            jQuery("input#" + myId).val(jQuery("select[id='" + selectId + "'] option:selected").text().split(" - ")[0]);
            jQuery(this).hide("fade", {}, 300);
        });
        if (typeof(options) == "string") {
            var methodName = options;
            options = {};
            for (var fld in $.hsInput.defaults) {
                options[fld] = jQuery(item).attr("plugin_" + fld);
            }
            if (methodName== "openlist") {
                showHS2Selection({
                    inputHS : ""
                }, options);
            } else if (methodName == "closelist") {
                hideList();
            } else if (methodName == "openfilteredlist") {
                showHS4Selection({inputString : arg.filter});
            }
            // methods
        } else {
            var timeout;
            jQuery("input#" + myId)
            .keyup(function(e) {
                if (jQuery(this).val() != "") {
                    keyupfunction(this, e, {
                        inputHS : jQuery(this).val()
                    });
                }
            });
            jQuery(item).keyup(function(e) {
                if (jQuery(this).val() != "") {
                    keyupfunction(this, e, {
                        inputString : jQuery(this).val()
                    });
                }
            });
        }

        var hs4selected = function(selecteditem) {
            jQuery("div.hsinput_select").hide("fade", {}, 300);
            var id = jQuery(selecteditem).text();
            var code = jQuery(selecteditem).attr("id");
            var engDesc = id.split(" - ")[1];
            var hunDesc = id.split(" - ")[2];
            jQuery(item).attr("datavalue", id);
            if (options.selected) {
                result = options.selected(item, id, code, hunDesc, engDesc);
                if (!result) { return; }
            }
            jQuery("input#" + myId).val(id);
        }

        var hs2clicked = function(id) {
            if (openedHS2.exists(id)) {
                jQuery("div#" + id + " div").hide("slide", {
                    direction : "up"
                }, 400);
                openedHS2.remove(id);
            } else {
                if (loadedHS2.exists(id)) {
                    jQuery("div#" + id + " div").show("slide", {
                        direction : "up"
                    }, 400);
                } else {
                    loadedHS2.push(id);
                    callService(options.page, options.hs4service, {
                        hs2code : id
                    }, {
                        success : function(result) {
                            for (var i = 0; i < result.items.length; i++) {
                                jQuery("div#" + id + " div")
                                    .append(
                                        jQuery("<span>")
                                            .html(result.items[i].hscode + " - " + result.items[i].description_en + " <b>-</b> " + result.items[i].description_hu)
                                            .attr("id", result.items[i].hscode)
                                            .addClass("hs4title")
                                            .click(function() { hs4selected(this); })
                                            .mouseover(function() { jQuery(this).addClass("highlighted"); })
                                            .mouseout(function() { jQuery(this).removeClass("highlighted"); })
                                    )
                                ;
                            }
                            jQuery("div#" + id + " div").show("slide", {
                                direction : "up"
                            }, 400);
                        }
                    });
                }
                openedHS2.push(id);
            }
        }

        var addHS2Item = function(item, hs2data) {
            item
                .append(
                    jQuery("<div>")
                        .addClass("hs2")
                        .attr("id", hs2data.chapter)
                        .mouseover(function() { jQuery(this).addClass("highlighted"); })
                        .mouseout(function() { jQuery(this).removeClass("highlighted"); })
                        .append(jQuery("<span>")
                            .addClass("hs2title")
                            .html(hs2data.chapter + " - " + hs2data.name_en + " <b>-</b> " + hs2data.name_hu)
                            .click(function() {
                                jQuery(this).parents("div").first().removeClass("highlighted");
                                hs2clicked(jQuery(this).parents("div").first().attr("id"));
                            })
                            .dblclick(function() { hs2selected(jQuery(this).parents("div").first().attr("id")); })
                        )
                        .append(jQuery("<div>")
                            .addClass("hs4block")
                            .hide()
                        )
                )
            ;
        }

        var hs2selected = function(id) {
            jQuery("input#" + myId).val(id);
            jQuery("div.hsinput_select").hide("fade", {}, 300);
        }

        var keyupfunction = function(kpitem, e, params) {
            if (!jQuery(kpitem).hasClass("textentered")) {
                jQuery(kpitem).addClass("textentered");
            }
            openedHS2 = [];
            loadedHS2 = [];
            if (options.change) {
                options.change();
            }
            var code = (e.keyCode ? e.keyCode : e.which);
            for (var fld in options.extraParams) {
                params[fld] = options.extraParams[fld];
            }
            if (options.enterHandler != null && code == 13) {
//                options.enterHandler(params);
                return;
            }
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            timeout = setTimeout(function() {
                if (params.inputHS !== undefined) {
                    showHS2Selection(params, options);
                } else {
                    showHS4Selection(params, options);
                }
            }, 800);
        }

        $.hsInput.defaults = {
            page : "",
            service : "",
            defaulttext : "",
            hs2service : "",
            hs4service : "",
            requestUrl : "",
            freetextservice : "",
            extraParams : {},
            enterHandler : null,
            emptyOnFocus : false,
            offsetLeft : 0,
            offsetTop : 0
        }
        $.hsInput.options = { }
    }
})(jQuery);

jQuery(window).click(function(e) {
    var ev = (e ? e : window.event);
    var element = (ev.target ? ev.target : ev.srcElement);
    if (!jQuery(element).hasClass("hsinput_select")) {
        jQuery("select.hsinput_select").hide("fade", {}, 300);
    }
});
